package com.qianyu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qianyu.entity.bean.QqAccount;
import com.qianyu.entity.bean.Qun;
import com.qianyu.entity.vo.QunVo;
import com.qianyu.mapper.QunMapper;
import com.qianyu.service.QhService;
import com.qianyu.service.QqAccountService;
import com.qianyu.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class QhServiceImpl implements QhService {

    private final QqAccountService qqAccountService;

    private final QunMapper qunMapper;

    private final RedisUtil redisUtil;

    @Override
    public Object qh(String cache) {
        List<QqAccount> list = qqAccountService.list();
        Map<String, String> map = list.stream().collect(Collectors.toMap(QqAccount::getQq, QqAccount::getProvinceCode));
        QunVo.QunSimpleVo simpleVo = new QunVo.QunSimpleVo();
        if (redisUtil.hasKey(cache)) {
            if (redisUtil.rGet(cache) != null) {
                simpleVo = BeanUtil.copyProperties(qunMapper.selectById((Long) redisUtil.rGet(cache)), QunVo.QunSimpleVo.class);
            }
        } else {
            simpleVo = BeanUtil.copyProperties(qunMapper.selectOne(Wrappers.<Qun>lambdaQuery().select(Qun::getId, Qun::getName, Qun::getQq, Qun::getPwd)
                    .eq(Qun::getStatus, 0).last(" limit 1")), QunVo.QunSimpleVo.class);
        }
        if (simpleVo != null) {
            simpleVo.setProvinceCode(map.get(simpleVo.getQq()));
        }
        return simpleVo;
    }
}
